package com.mobilesales.android.infrastructure;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

import com.mobilesales.android.R;
import com.mobilesales.android.util.MessageBox;

public class SyncTask extends AsyncTask<Void,Integer,Boolean> implements IProgressUpdater {
    
	Context ctx;
	ProgressDialog dialog;
	
	public SyncTask(Context ctx) {
		this.ctx = ctx;
	}
	
	@Override
    protected void onPreExecute() {
		dialog = new ProgressDialog(ctx);
		dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		dialog.setMessage(ctx.getString(R.string.SyncLoading));
		dialog.setCancelable(false);
		dialog.show();
    }
	
	@Override
	protected Boolean doInBackground(Void... params) {
		SyncService syncService = new SyncService(ctx,this);
		boolean success = syncService.synchronize();
		return success;
	}
	
	@Override
	protected void onProgressUpdate(Integer... prog) {
		dialog.setProgress(prog[0]);
	}
	
	public void onProgressUpdated(int progress) {
		this.publishProgress(progress);
	}		

	@Override
    protected void onPostExecute(Boolean success) {
		dialog.dismiss();
		if (success)
			MessageBox.show(ctx, ctx.getString(R.string.SyncSuccessful));
		else
			MessageBox.show(ctx, ctx.getString(R.string.ErrorSync));
    }


	
}
